package org.jmc.refmanager.web.wicket.markup.html.secured.link;

import org.apache.wicket.Page;
import org.apache.wicket.PageParameters;
import org.apache.wicket.authentication.AuthenticatedWebApplication;
import org.apache.wicket.authorization.strategies.role.Roles;
import org.apache.wicket.authorization.strategies.role.annotations.AuthorizeAction;
import org.apache.wicket.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;

public class SecuredLink<T> extends BookmarkablePageLink<T> {
	private static final long serialVersionUID = 1L;
	private Class<? extends Page> pageClass;
	
	/**
	 * @param id
	 * @param pageClass
	 * @param parameters
	 */
	public <C extends Page> SecuredLink(String id, Class<C> pageClass, PageParameters parameters) {
		super(id, pageClass, parameters);
		this.pageClass = pageClass;
	}

	/**
	 * @param id
	 * @param pageClass
	 */
	public <C extends Page> SecuredLink(String id, Class<C> pageClass) {
		super(id, pageClass);
		this.pageClass = pageClass;
	}

	@Override
	public boolean isVisible() {
		boolean isVisible = super.isVisible();
		boolean authorized = true;
		AuthorizeInstantiation authzInstanceAnnot = this.pageClass.getAnnotation(AuthorizeInstantiation.class);
		AuthorizeAction authzAction = this.pageClass.getAnnotation(AuthorizeAction.class);
		AuthenticatedWebApplication app = (AuthenticatedWebApplication) AuthenticatedWebApplication.get();
		
		if (authzInstanceAnnot != null) {
			// Ne pas afficher un lien si les reles d'instanciation ne correspondent pas
			authorized = app.hasAnyRole(new Roles(authzInstanceAnnot.value()));
			return authorized && isVisible;
		} else if (authzAction != null) {
			String[] denyRoles = authzAction.deny();
			if (denyRoles != null) {
				authorized &= !app.hasAnyRole(new Roles(denyRoles));
			}
			String[] authRoles = authzAction.roles();
			if (authRoles != null) {
				authorized &= app.hasAnyRole(new Roles(authRoles));
			}
			return authorized && isVisible;
		}
		
		return isVisible;
	}
}
